package com.youwu.demo02.FileUpload;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class TCPServer {

    public static void main(String[] args) throws IOException {
        ServerSocket server = new ServerSocket(8888);
        Socket socket = server.accept();

        InputStream is = socket.getInputStream();

        File file = new File("d:\\upload");
        if(!file.exists()) {
            file.mkdirs();
        }

        FileOutputStream fos = new FileOutputStream(file + "\\1.jpg");
        byte[] bytes = new byte[1024];
        int len = 0;
        // is.read(bytes)读取客户端上传文件，永远也读取不到结束标记
        // 因此，当文件上传成功后，read方法会进入到阻塞状态，导致服务器无法关闭
        while (-1 != (len = is.read(bytes))) {
            fos.write(bytes, 0, len);
        }

        OutputStream os = socket.getOutputStream();
        os.write("上传成功！".getBytes());

        fos.close();
        socket.close();
        server.close();
    }
}
